package com.moli.iov.gateway.config;

import com.moli.iov.util.SnowflakeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *
 * </p>
 *
 * @Auther: zql
 * @Date: 2019/1/31 16:08
 */
@Configuration
public class KafkaConfig {

    private static final Logger logger = LoggerFactory.getLogger(KafkaConfig.class);

    @Value("${kafka.consumer.bootstrap.servers}")
    private String kafkaConsumerBootstrapServers;

    @Value("${kafka.consumer.enable.auto.commit}")
    private String kafkaConsumerEnableAutoCommit;

    @Value("${kafka.consumer.auto.commit.interval.ms}")
    private String kafkaConsumerAutoCommitIntervalMs;

    @Value("${kafka.consumer.session.timeout.ms}")
    private String kafkaConsumerSessionTimeoutMs;

    @Value("${kafka.consumer.key.deserializer}")
    private String kafkaConsumerKeyDeserializer;

    @Value("${kafka.consumer.value.deserializer}")
    private String kafkaConsumerValueDeserializer;

    @Value("${server.name}")
    private String serverName;

    @Value("${netty.server.port}")
    private String nettyServerPort;


    @Bean
    public Map<String, Object> consumerProperties(){
        Map<String, Object> configs = new HashMap<>();
        configs.put("bootstrap.servers", kafkaConsumerBootstrapServers);
        configs.put("group.id", getKafkaGroupId());
        configs.put("enable.auto.commit", kafkaConsumerEnableAutoCommit);
        configs.put("auto.commit.interval.ms", kafkaConsumerAutoCommitIntervalMs);
        configs.put("session.timeout.ms", kafkaConsumerSessionTimeoutMs);
        configs.put("key.deserializer", kafkaConsumerKeyDeserializer);
        configs.put("value.deserializer", kafkaConsumerValueDeserializer);

        return configs;
    }

    /**
     * 获取Kafka消费者组id
     * groupId = IP + 端口 + 服务名
     * @return
     */
    private String getKafkaGroupId(){
        StringBuffer sb = new StringBuffer();

        sb.append(getIp());
        sb.append("AND");
        sb.append(nettyServerPort);
        sb.append("AND");
        sb.append(serverName);

        String groupId = sb.toString();

        logger.info("Kafka消费者组id：{}", groupId);
        return groupId;
    }

    Random ra =new Random();
    /**
     * 获取IP地址
     * @return
     */
    private String getIp(){
        try {

            return SnowflakeUtils.getId();
        } catch (Exception e) {
            logger.error("获取IP地址 异常", e);
        }
        return String.valueOf(ra.nextInt(10000));
    }
}

